import { Injectable } from '@angular/core';
import { SessionStorageService } from '../shared/storage/session-storage.service';

import {HttpService} from '../shared/http/http.service';
import {ConfigProvider} from '../providers/config.provider';

import {ProfileModel} from '../models/ProfileModel';
/*
* 帐号服务
*/
@Injectable()
export class PassportService {

    constructor(
        private sessionStorageService: SessionStorageService,
        private httpService: HttpService
    ) {

    }
    public logout() {
        this.sessionStorageService.remove('Profile');
        this.sessionStorageService.remove('AppInfo');
    }

    public setProfile(profile) {
        this.sessionStorageService.setObject('Profile', profile);
        this.sessionStorageService.setObject('AppInfo', profile.appInfo);
    }

    public login(loginData, callback: Function) {
        const that = this;
        const loginUrl = ConfigProvider.passportBaseURL + 'cms/passport/login';
        this.httpService.post(loginUrl, loginData, function (successful, data, res) {
          if (successful && callback) {
              const profile = (<ProfileModel>data.result);
              that.setProfile(profile);
              callback(true, profile);
          }
        }, function (successful, msg, err) {
            if (callback) {
                console.log(msg);
                callback(false, err);
            }
        });
    }

    public getProfile(): ProfileModel {
        const profile = (<ProfileModel>JSON.parse(this.sessionStorageService.get('Profile')));
        return profile;
    }

    public isAuthenticated() {
        const profile = this.sessionStorageService.get('Profile');
        return profile ? true : false;
    }


}
